<?php
/**
 * User: wufeng
 * Date: 2019/4/17
 * Time: 15:01.
 */

namespace app\api\controller;

use app\api\service\SxfApiService;
use app\models\MerchantModel;
use app\models\MerchantPaytypeModel;
use app\models\RefundAmountModel;
use think\Log;

class Refund extends Common
{
    /**
     * 退款操作.
     *
     * @throws \think\Exception
     * @throws \think\exception\DbException
     *
     * @return array|mixed|\SimpleXMLElement|\think\response\Json
     */
    public function refund()
    {
        $refund_voucher = input('refund_voucher');
        $receipt_number = input('receipt_number');
        $refundAmount = RefundAmountModel::get(['receipt_number' => $refund_voucher])->toArray();
        if ('117' == $refundAmount['refund_channel'] || '118' == $refundAmount['refund_channel'] || '120' == $refundAmount['refund_channel']) {
            Log::record('随行付退款入口', 'refund');

            return $this->sxfRefund($refundAmount, $receipt_number);
        }
        //		elseif (){
//
//		}
//		return $res;
    }

    /**
     * 随行付退款
     * User: wufeng
     * Date: 2019/4/18.
     *
     * @param $refundAmount
     * @param $receipt_number
     *
     * @throws \think\exception\DbException
     *
     * @return array
     */
    public function sxfRefund($refundAmount, $receipt_number)
    {
        $merchantPaytype = MerchantPaytypeModel::get(['pay_type' => $refundAmount['refund_channel']]);
        $mch = MerchantModel::get($merchantPaytype['merchant_id']);

        $refundData['orgId'] = $mch['mch_appid']; //机构ID
        $refundData['reqId'] = $receipt_number; //订单号
        $refundData['signType'] = 'RSA'; //签名类型
        $refundData['timestamp'] = date('Ymdhis'); //请求时间：时间戳
        $refundData['version'] = '1.0'; //版本
        //对应业务信息
        $refundData['reqData'] = [
            'ordNo' => $refundAmount['receipt_number'],
            'mno' => $mch['mch_number'],
            'origOrderNo' => $receipt_number,
            'amt' => $refundAmount['amount'] / 100,
            'notifyUrl' => 'http://'.$_SERVER['HTTP_HOST'].'/api/Notify/refundNotify', //回调地址,
        ];
        Log::record('请求参数='.json_encode($refundData), 'refund');
        $req = json_encode($refundData);

        //提交服务器url
        $url = 'https://icm-management.suixingpay.com/management/qr/refund'; //正式地址
        $res = json_decode((new SxfApiService())->sxf($req, $url), true);
        if ('SXF0000' === $res['code']) {
            $result = $res['respData']; //payUrl
            Log::record('返回参数='.json_encode($result), 'refund');

            return ['code' => $result['bizCode'], 'msg' => $result['bizMsg']];
        }

        return ['code' => $res['code'], 'msg' => $res['msg']];
    }
}
